// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// C [author] rhyme_lph
// g [email]  rhymelph@gmail.com
// y [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/src/entities/plans_item_entity.dart';
import 'package:finance_app/src/entities/plans_subscription_entity.dart';
import 'package:finance_app/src/entities/sub_billing_item_entity.dart';
import 'package:finance_app/src/http_service/http_subscription_service.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/cash_utils.dart';

import '../subscription_provider.dart';

class SubCompanyProvider extends BaseProvider {
  List<SubBillingItemEntity> pastBills = [];
  SubBillingItemEntity subBillingItem;

  @override
  Future get dataFuture => null;

  @override
  void initState() {
    super.initState();
    loadPastBills();
  }

  Future<void> loadPastBills() async {
    await post(
        HttpSubscriptionService.getSubBillHistory(
            companyID: subBillingItem.companyId),
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      pastBills = getEntityFromResult(result);
      update();
    });
  }

  void onNavBillDetail(SubBillingItemEntity value) {
    Routes.navigateTo(RouterGenProviders.subInvoicePage, params: {
      'id': value.id,
    });
  }

  void onPay() async {
    List<PlansItemEntity> plans = [];
    await post(
        HttpSubscriptionService.getSubscriptionsPlans(
          type: 'monthly',
        ),
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      PlansSubscriptionEntity d =
          getEntityFromResult<PlansSubscriptionEntity>(result);
      plans.addAll(d.plans);
    });
    await post(
        HttpSubscriptionService.getSubscriptionsPlans(
          type: 'yearly',
        ),
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      PlansSubscriptionEntity d =
          getEntityFromResult<PlansSubscriptionEntity>(result);
      plans.addAll(d.plans);
    });

    final result =
        await Routes.navigateTo(RouterGenProviders.subPaymentPage, params: {
      'plan': PlansItemEntity()
        ..id = subBillingItem.planId
        ..price = CashUtils.formatCashAmount(subBillingItem.originalPrice)
        ..upgradePrice = CashUtils.formatCashAmount(subBillingItem.price)
        ..nameText = subBillingItem.planName
        ..issuesDate = subBillingItem.issuedAt
        ..dueAt = subBillingItem.dueAt
        ..type = plans
            .firstWhere((element) => element.id == subBillingItem.planId)
            .type,
      'billId': subBillingItem.id,
      'companyId': subBillingItem.companyId,
      'companyName': subBillingItem.companyName,
      'previousEndDate': subBillingItem.endAt
    });
    if (result == true) {
      getParentProvider<SubscriptionProvider>().onTry();
    }
  }
}
